package com.tianhui.consignortwofei.other.auth.ocr;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.tianhui.consignortwofei.constant.OcrKey;
import com.tianhui.consignortwofei.other.auth.recognition.IRecognition;
import com.tianhui.consignortwofei.utils.ApplicationUtil;

/**
 * @author fgs
 * @date 2021/5/14
 * @description
 **/
public class BaiDuOcrRecognition implements IOcrRecognition {
    IRecognition iRecognition;

    public BaiDuOcrRecognition(IRecognition iRecognition) {
        this.iRecognition = iRecognition;
        initAccessTokenWithAkSk();
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance(ApplicationUtil.getContext()).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                LogUtil.print("BaiDuOcrRecognition--OCR_AK_SK_token", token);

            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                LogUtil.print("AK，SK方式获取token失败" + error.getMessage());
                ToastUtil.showShortToast(getOCRErrorMessage(error.getErrorCode()));
            }
        }, ApplicationUtil.getContext(), OcrKey.BAI_DU_OCR_AK, OcrKey.BAI_DU_OCR_SK);
    }

    private String getOCRErrorMessage(int errorCode) {
        String errorMsg = "OCR 初始化失败";
        switch (errorCode) {
            case 110:
                errorMsg = "OCR Access Token 过期";
                break;
            case 283504:
                errorMsg = "OCR 网络请求失败，请保证网络通畅";
                break;
            case 283505:
                errorMsg = "OCR 服务器返回数据异常";
                break;
            case 283602:
                errorMsg = "时间戳不正确，请确保不要改变调用设备的本地时间";
                break;
            case 283700:
                errorMsg = "OCR 服务器内部错误";
                break;
        }

        return errorMsg;
    }


    @Override
    public IRecognition recognition() {
        return iRecognition;
    }
}
